package com.example.memolaga.credentials;

import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

import com.example.memolaga.Constants;
import com.example.memolaga.R;


import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.content.Context;


public class CredAdd extends Activity {
	
	private String sKey;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle bundle = this.getIntent().getExtras();
		if (bundle!=null)
			this.sKey = bundle.getString(Constants.getKeyString());
		else
			Log.i("CredAdd","sKey null");
        //Log.i("onCreateCard","Skey: "+this.sKey);
		setContentView(R.layout.cred_add);
		Button btnSave = (Button) findViewById(R.id.btnCredSave);
		btnSave.setOnClickListener(saveCredListener);

		
	}

    private OnClickListener saveCredListener = new OnClickListener()
    {

		@Override
		public void onClick(View view) {
			String name = ((EditText) findViewById(R.id.editCredentialName)).getText().toString();
			String user = ((EditText) findViewById(R.id.editCredentialUser)).getText().toString();
			String password = ((EditText) findViewById(R.id.editCredentialPass)).getText().toString();
			String dateCreated = ((EditText) findViewById(R.id.editCredentialDateCreated)).getText().toString();
			String dateLastUsed = ((EditText) findViewById(R.id.editCredentialDateLastUsed)).getText().toString();
			String dateExpiry = ((EditText) findViewById(R.id.editCredentialExpiry)).getText().toString();
			String site = ((EditText) findViewById(R.id.editCredentialSite)).getText().toString();
			String note = ((EditText) findViewById(R.id.editCredentialNote)).getText().toString();
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
            if (preferences.getBoolean(Constants.getPrefStringShowPass(), Constants.getPrefDefaultShowPass()))
            {
                ((ImageView) findViewById(R.id.imgCredAddUser)).setVisibility(View.GONE);
                ((TextView) findViewById(R.id.editCredentialUser)).setInputType(InputType.TYPE_CLASS_NUMBER);
                ((ImageView) findViewById(R.id.imgCredAddPass)).setVisibility(View.GONE);
                ((TextView) findViewById(R.id.editCredentialPass)).setInputType(InputType.TYPE_CLASS_NUMBER);
            }
            ((ImageView) findViewById(R.id.imgCredAddUser)).setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View view) {
                    if (((EditText) findViewById(R.id.editCredentialUser)).getInputType()!= InputType.TYPE_CLASS_NUMBER)
                    {
                        ((ImageView) findViewById(R.id.imgCredAddUser)).setImageDrawable(getResources().getDrawable(R.drawable.secure2));
                        ((EditText) findViewById(R.id.editCredentialUser)).setInputType(InputType.TYPE_CLASS_NUMBER);
                    }
                    else
                    {
                        ((ImageView) findViewById(R.id.imgCredAddUser)).setImageDrawable(getResources().getDrawable(R.drawable.not_secure2));
                        ((EditText) findViewById(R.id.editCredentialUser)).setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
                    }
                }
            });
            ((ImageView) findViewById(R.id.imgCredAddPass)).setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View view) {
                    if (((EditText) findViewById(R.id.editCredentialPass)).getInputType()!= InputType.TYPE_CLASS_NUMBER)
                    {
                        ((ImageView) findViewById(R.id.imgCredAddPass)).setImageDrawable(getResources().getDrawable(R.drawable.secure2));
                        ((EditText) findViewById(R.id.editCredentialPass)).setInputType(InputType.TYPE_CLASS_NUMBER);
                    }
                    else
                    {
                        ((ImageView) findViewById(R.id.imgCredAddPass)).setImageDrawable(getResources().getDrawable(R.drawable.not_secure2));
                        ((EditText) findViewById(R.id.editCredentialPass)).setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
                    }
                }
            });
			ArrayList<CredentialMaster> cTot = CredentialManager.getInstance().credAdd(name, user, password, dateCreated, dateLastUsed, dateExpiry, site, note, sKey);
			if (writeNewFile(Constants.getPathCredentialsFile(),CredentialManager.getInstance().getStringToWrite(cTot)))
            {
                Toast.makeText(getBaseContext(), R.string.strOKCreateFile, Toast.LENGTH_LONG).show();
                Intent i = getIntent();
                setResult(Constants.getResultEdit());
                finish();
            }
			else
				Toast.makeText(getBaseContext(), R.string.strErrorCreateFile, Toast.LENGTH_LONG).show();
		}
    	
    };
    
	private boolean writeNewFile(String pathFile, String toWrite)
	{
		boolean ret = true;
		Log.i("CA writeNewFile I: ",toWrite);
		File f = new File(pathFile);
		if (f.exists())
		{
			Log.i("CA writeNewFile I: ","File exists");
			File to =new File(pathFile+".bak");
			f.renameTo(to);
		}
		try
		{
			OutputStreamWriter osw = new OutputStreamWriter(openFileOutput(pathFile, Context.MODE_PRIVATE)); 
			osw.write(toWrite);
		    osw.flush();
		    osw.close();
		}
		catch (IOException eIO)
		{
			Log.e("CA writeNewFilea IO ",eIO.getMessage());
			ret=false;
		}
		catch (Exception e)
		{
			Log.e("CA writeNewFile E ",e.getMessage());
			ret=false;
		}
		return ret;
	}
	
	/*@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.cred_ad, menu);
		return true;
	}*/

}
